<template>
  <div class="files-upload">
    <t-upload
      v-model="files"
      :placeholder="`支持批量上传文件，最多只能上传 ${max} 份文件`"
      :disabled="disabled"
      :multiple="multiple"
      :max="max"
      :action="action"
      :autoUpload="autoUpload"
      :theme="theme"
      :sizeLimit="sizeLimit"
      :abridgeName="abridgeName"
      :draggable="draggable"
      :formatResponse="formatResponse"
      :headers="{ Authorization: `Bearer ${this.token}` }"
      @one-file-success="oneFileSuccess"
      @remove="remove"
    >
      <slot name="pic"></slot>
    </t-upload>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import { BASE_URL } from '@/service/request/config';
import { FILE_URL_PREFIX } from '@/constants/index';

function getCurrentDate(needTime = false) {
  const d = new Date();
  let month = d.getMonth() + 1;
  month = month < 10 ? `0${month}` : month;
  const date = `${d.getFullYear()}-${month}-${d.getDate()}`;
  const time = `${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}`;
  if (needTime) return [date, time].join(' ');
  return date;
}

export default {
  name: 'filesUpload',
  props: {
    value: {
      type: Array,
      default() {
        return [];
      },
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    autoUpload: {
      type: Boolean,
      default: true,
    },
    theme: {
      type: String,
      default: 'file-flow',
    },
    max: {
      type: Number,
      default: 10,
    },
    multiple: {
      type: Boolean,
      default: true,
    },
    abridgeName: {
      type: Array,
      default() {
        return [8, 4];
      },
    },
    draggable: {
      type: Boolean,
      default: true,
    },
    sizeLimit: {
      type: Number,
      default: 10000,
    },
  },
  data() {
    return {
      action: '',
    };
  },
  computed: {
    ...mapGetters({
      token: 'user/token',
    }),
    files: {
      set(val) {
        this.$emit('input', val);
      },
      get() {
        return this.value;
      },
    },
  },
  mounted() {
    this.action = `${BASE_URL}/common/upload`;
  },
  methods: {
    // res.url 图片地址；res.uploadTime 文件上传时间；res.error 上传失败的原因
    formatResponse(res) {
      // 响应结果添加上传时间字段，用于 UI 显示
      res.uploadTime = getCurrentDate(true);
      if (res.code === 200) {
        this.$emit('returnRes', res.data);
      }
      return res;
    },
    oneFileSuccess(context) {
      context.file.path = context.response.data;
      context.file.url = FILE_URL_PREFIX + context.response.data;
      this.$emit('oneFileSuccess', context);
    },
    remove({ file }) {
      this.$emit('oneFileRemove', file.id);
    },
  },
};
</script>

<style lang="less" scoped>
.files-upload {
  width: 100%;
  /deep/ .t-upload__flow {
    min-width: 434px;
    tbody tr td {
      padding: 10px 18px;
    }
  }
}
</style>
